package com.mgface.foundation.framework.core.http;

import org.apache.coyote.http11.Http11NioProtocol;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.Compression;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.SocketUtils;

import java.util.concurrent.TimeUnit;

/**
 * 自定义内嵌servlet容器
 * @author wanyuxiang
 *
 */
@Configuration
public class HttpTomcatEmbeddedServletContainerFactory {
	private static final Logger log = LogManager.getLogger(HttpTomcatEmbeddedServletContainerFactory.class);
	@Value("${system.http-port:0}")
	private int port;
	@Value("${system.contextpath:/member}")
	private String contextPath;

	@Bean
	public Integer port() {
		if (port == 0) {
			port = SocketUtils.findAvailableTcpPort();
		}
		log.info("获取有效的端口值:{}", port);
		return port;
	}

	@Bean
	public EmbeddedServletContainerFactory servletContainer() {
		TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(port());
		tomcat.addConnectorCustomizers(connector -> {
			connector.setAsyncTimeout(5000L);
			connector.addLifecycleListener(e -> log.info("生命周期阶段:{}", e.getType()));
			Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
			//设置最大连接数
			protocol.setMaxConnections(2000);
			//设置最大线程数
			protocol.setMaxThreads(2000);
			protocol.setConnectionTimeout(30000);
		});
		tomcat.setSessionTimeout(1, TimeUnit.SECONDS);
		Compression compression = new Compression();
		compression.setEnabled(true);
		tomcat.setCompression(compression);
		tomcat.setContextPath(contextPath);
		return tomcat;
	}
}
